﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using AviationSimulator.DataItems;
using AviationSimulator.Properties;
using AviationSimulator.UDP;

namespace AviationSimulator.Managers
{
    public class NetworkManager
    {
        public void SendPackage(Package package, string ipAddress, int port)
        {
            var modelMessage = new ModelMessage();

            foreach (var parameter in package.Parameters)
            {
                modelMessage.AddParameter(parameter.Name, parameter.Value);
            }

            string xmlStructure = modelMessage.ToString();

            var datagram = new Datagram { MessageBody = xmlStructure, PackageType = PackageTypes.Info };

            using (var transmitter = new Transmitter(IPAddress.Parse(Settings.Default.LocalIP), Settings.Default.LocalPort))
            {
                transmitter.Send(datagram, ipAddress, port);
            }
        }

        public Package ReceivePackage(string ipAddress, int port)
        {
            Datagram datagram;

            using (var receiver = new Receiver())
            {
                datagram = receiver.ReceiveDatagram(ipAddress, port);
            }

            var modelMessage = new ModelMessage(datagram.MessageBody);

            if (datagram.PackageType == PackageTypes.Info)
            {
                var package = new Package { TimeStamp = DateTime.Now };
                
                foreach (DictionaryEntry parameter in modelMessage.Parameters)
                {
                    var packageParameter = new Parameter { Name = parameter.Key.ToString(), Value = parameter.Value.ToString() };
                    package.Parameters.Add(packageParameter);
                }

                return package;
            }

            return ReceivePackage(ipAddress, port);
        }
    }
}
